
let nums=[6,1,2,3,4,5];
let target=5;

// 方法1

// var dfs = function(nums, target, start){
//   for (let i = start + 1; i < nums.length; i++) {
//     if(nums[i] == target-nums[start]) return i;
//   }
//   return false;
// }
// var twoSum = function(nums, target) {
//   for (let i = 0; i < nums.length; i++) {
//     let second = dfs(nums, target, i);
//     if(second) return [i, second];
//   }
// }


// 方法2 二分查找第二个值的下标


var binary_search = function(nums, indexs, target, start){
  let head=start+1;
  let tail=indexs.length-1;
  while(head<=tail){
    let mid=head+(tail-head>>1);
    if(nums[indexs[mid]]==target){
      return indexs[mid];
    }
    if(nums[indexs[mid]]<target){
      head=mid+1;
    }else{
      tail=mid-1;
    }
  }
  return -1
}

var twoSum = function(nums, target) {
  let indexs = [];
  for (let i = 0; i < nums.length; i++) indexs[i] = i;
  indexs.sort((a,b)=> nums[a] - nums[b]);
  console.log('indexs',indexs);
  for(let i = 0; i < indexs.length; i++){
    let j = binary_search(nums, indexs, target - nums[indexs[i]], i);
    if(j != -1) return [indexs[i], j];
  }
}


console.log(twoSum(nums, target));